package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.MemberThreadLocal;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.domain.PropertyStatusInfo;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.dto.PageQueryDto;
import com.zzyl.nursing.dto.QueryDeviceDataListDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.mapper.FamilyMemberElderMapper;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.LoginVo;
import com.zzyl.nursing.vo.MyFamilyPageVo;
import com.zzyl.nursing.vo.MyFamilyVo;
import com.zzyl.nursing.vo.QueryDeviceDataListVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 老人家属Service业务层处理
 *
 * @author JBY
 * @date 2025-08-20
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {

    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;

    @Autowired
    private DeviceDataMapper deviceDataMapper;

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     *//*
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return familyMemberMapper.selectById(id);
    }

    *//**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     *//*
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    *//**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     *//*
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return familyMemberMapper.insert(familyMember);
    }

    *//**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     *//*
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return familyMemberMapper.updateById(familyMember);
    }

    *//**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     *//*
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return familyMemberMapper.deleteBatchIds(Arrays.asList(ids));
    }

    */

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     *//*
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return familyMemberMapper.deleteById(id);
    }*/

    /**
     * 老人家属登录
     *
     * @param userLoginRequestDto
     * @return LoginVo
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        // 1. 获取OpenId
        String openId = wechatService.getOpenid(userLoginRequestDto.getCode());
        //2.根据openid查询库老人家属信息
        FamilyMember member = this.lambdaQuery()
                .eq(FamilyMember::getOpenId, openId)
                .one();
        // 3.判断老人家是否为空
        if (Objects.isNull( member)) {
            member =new FamilyMember();


        }
        // 4. 根据detail.code, 向微信发请求获取手机号
        String phoneNumber = wechatService.getPhoneNumber(userLoginRequestDto.getPhoneCode());
        member.setPhone(phoneNumber);
        String nickName = Constants.DEFAULT_NICKNAME_PREFIX
                .get(RandomUtil.randomInt(0, Constants.DEFAULT_NICKNAME_PREFIX.size()))
                .concat(phoneNumber.substring(phoneNumber.length() - 4));
        if(StringUtils.isBlank(member.getRemark())){
            member.setRemark(nickName);

        }
        // 5. 新增或修改用户信息
        saveOrUpdateFamilyMember( member);
        //6.使用封装数据
        //使用HUTOOL生成一个0，10位的随机数
        Map<String , Object> clamis = new HashMap<>();
        clamis.put("memberId", member.getId());
        clamis.put("nickName", member.getRemark());
        String token= tokenService.createToken(clamis);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(member.getRemark());
        return loginVo;

    }
    /**
     * 查询家人列表
     * @param
     * @return
     */

    @Override
    public List<MyFamilyVo> selectMyFamily() {
        //获取用户ID
        Long userId = MemberThreadLocal.getMemberId();
        List<Long> ids = familyMemberElderMapper.selectMyFamily(userId);
         List<MyFamilyVo> elder =  elderMapper.selectMyFamily(ids);
         elder.forEach(e -> {e.setFamilyMemberId(userId);});
         return elder;


    }
    /**
     * 分页查询
     * @param
     * @return
     */

    @Override
    public List<MyFamilyPageVo> listByPage(PageQueryDto pageQueryDto) {
        Page<MyFamilyPageVo> page = new Page<>(pageQueryDto.getPageNum(), pageQueryDto.getPageSize());
        List<MyFamilyPageVo> myFamilyPageVos = familyMemberMapper.selectFamily(MemberThreadLocal.getMemberId());
        return myFamilyPageVos;
    }


    private void saveOrUpdateFamilyMember(FamilyMember familyMember) {
        if (ObjectUtils.isNull(familyMember.getId())) {
            save(familyMember);
        } else {
            updateById(familyMember);
        }
    }

    /**
     * 查询设备属性状态
     *
     * @param deviceDto
     * @return List<PropertyStatusInfo>
     */
    @Override
    public List<PropertyStatusInfo> QueryDevicePropertyStatus(DeviceDto deviceDto) {
        // DTO非空校验
        String deviceName = deviceDto.getDeviceName();
        String productKey = deviceDto.getProductKey();
        if (StrUtil.isEmpty(deviceName) || StrUtil.isEmpty(productKey)) {
            throw new BaseException("设备信息不能为空");
        }
        // 查询健康数据
        List<PropertyStatusInfo> deviceData = deviceDataMapper.selectdeviceDataList(deviceName, productKey);
        //根据identifier分配name
        deviceData.forEach(item -> {
            switch (item.getIdentifier()) {
                case "BodyTemp":
                    item.setName("温度");
                    item.setDataType("double");
                    break;
                case "xueyang":
                    item.setName("血氧");
                    item.setDataType("double");
                    break;
                case "HeartRate":
                    item.setName("率");
                    item.setDataType("int");
                    break;
                case "BatteryPercentage":
                    item.setName("电量");
                    item.setDataType("double");
                    break;
            }
        });
        return deviceData;
    }

    /**
     * 按天查询设备数据列表
     *
     * @param queryDeviceDataListDto
     * @return List<QueryDeviceDataListVo>
     */
    @Override
    public List<QueryDeviceDataListVo> queryDeviceDataListByDay(QueryDeviceDataListDto queryDeviceDataListDto) {
        Long startTime = queryDeviceDataListDto.getStartTime();
        Long endTime = queryDeviceDataListDto.getEndTime();
        //将毫秒值转为时间
        LocalDateTime startDate = LocalDateTime.ofInstant(Instant.ofEpochMilli(startTime), ZoneId.systemDefault());
        LocalDateTime endDate = LocalDateTime.ofInstant(Instant.ofEpochMilli(endTime), ZoneId.systemDefault());
        return deviceDataMapper.selectdeviceDataListByDay(queryDeviceDataListDto, startDate, endDate);
    }


    /**
     * 按周查询设备数据列表
     *
     * @param queryDeviceDataListDto
     * @return List<QueryDeviceDataListVo>
     */
    @Override
    public List<QueryDeviceDataListVo> queryDeviceDataListByWeek(QueryDeviceDataListDto queryDeviceDataListDto) {
        Long startTime = queryDeviceDataListDto.getStartTime();
        Long endTime = queryDeviceDataListDto.getEndTime();
        //将毫秒值转为时间
        LocalDateTime startDate = LocalDateTime.ofInstant(Instant.ofEpochMilli(startTime), ZoneId.systemDefault());
        LocalDateTime endDate = LocalDateTime.ofInstant(Instant.ofEpochMilli(endTime), ZoneId.systemDefault());
        return deviceDataMapper.selectdeviceDataListByWeek(queryDeviceDataListDto, startDate, endDate);
    }
}
